package com.aqie.meet.ui.my;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.aqie.libcommon.adapter.CommonAdapter;
import com.aqie.libcommon.adapter.CommonViewHolder;
import com.aqie.libcommon.app.BaseApplication;
import com.aqie.libcommon.utils.SimpleJsonTool;
import com.aqie.libcommon.utils.StatusBar;
import com.aqie.libcommon.view.EmptyView;
import com.aqie.libfactory.data.helper.DbHelper;
import com.aqie.libfactory.model.api.PageList;
import com.aqie.libfactory.model.api.RspModel;
import com.aqie.libfactory.model.api.chat.ChatPermission;
import com.aqie.libfactory.model.api.user.UserPost;
import com.aqie.libfactory.model.db.User;
import com.aqie.libfactory.net.Network;
import com.aqie.libfactory.net.RemoteService;
import com.aqie.meet.R;
import com.aqie.meet.databinding.ActivityFriendHomePageBinding;
import com.aqie.meet.ui.chat.MessageActivity;
import com.aqie.meet.ui.find.PostDetailActivity;
import com.aqie.meet.ui.login.AccountActivity;
import com.aqie.meet.utils.TimeUtils;
import com.aqie.meet.view.AImageView;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class FriendHomePageActivity extends AppCompatActivity {
    private String TAG = this.getClass().getSimpleName();
    private ActivityFriendHomePageBinding mBinding;
    protected Unbinder mRootUnBinder;
    private String talentsId;
    private String username;
    private Boolean isBoolFriend;
    // 聊天权限相关
    private ChatPermission chatPermission = null;

    @BindView(R.id.recycler_view)
    RecyclerView mRecycleView;

    @BindView(R.id.empty_view)
    EmptyView mEmptyView;

    @BindView(R.id.tag_avatar)
    AImageView mCircleTextImage;

    @BindView(R.id.btn_send_message)
    TextView sendMessage;

    @BindView(R.id.btn_add_friend)
    TextView mAddFriend;

    private List<UserPost> mList = new ArrayList<>();
    private CommonAdapter<UserPost> mAdapter;

    private User data;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        StatusBar.fitSystemBar(this);
        super.onCreate(savedInstanceState);
        Intent intent = getIntent();
        talentsId = intent.getStringExtra("talentsId");
        username = intent.getStringExtra("username");
        isBoolFriend = intent.getBooleanExtra("isBoolFriend", false);
        if(talentsId == null || talentsId.equals("")) {
            finish();
            return;
        }
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_friend_home_page);
        mRootUnBinder = ButterKnife.bind(this, mBinding.getRoot());
        initView();
        initData();
    }

    private void initData() {
        getMyBase();
        getMyPost();
    }

    private void getMyPost() {
        RemoteService service = Network.remote();
        Call<RspModel<PageList<UserPost>>> call = service.talentsPost(talentsId, 1, 1000);
        call.enqueue(new Callback<RspModel<PageList<UserPost>>>() {
            @Override
            public void onResponse(Call<RspModel<PageList<UserPost>>> call, Response<RspModel<PageList<UserPost>>> response) {
                RspModel<PageList<UserPost>> body = response.body();
                if(body !=null && body.success()){
                    PageList<UserPost> posts = body.getData();
                    String rspString = SimpleJsonTool.toJson(posts); Log.e(TAG, rspString);
                    if(posts.getTotal() == 0) {
                        mRecycleView.setVisibility(View.GONE);
                        mEmptyView.setVisibility(View.VISIBLE);
                    } else {
                        mRecycleView.setVisibility(View.VISIBLE);
                        mEmptyView.setVisibility(View.GONE);
                        if (mList.size() > 0) {
                            mList.clear();
                        }
                        mList.addAll(posts.getRecords());
                        mAdapter.notifyDataSetChanged();
                        Log.e(TAG, "my list:" + mList.toString());
                    }
                }else {
                    Log.e(TAG, "request fail: " + response.code());
                }
            }

            @Override
            public void onFailure(Call<RspModel<PageList<UserPost>>> call, Throwable t) {
                Log.e(TAG, "request fail: onFailure");
            }
        });
    }

    private void getMyBase() {
        RemoteService service = Network.remote();
        Call<RspModel<User>> call = service.talentBase(talentsId);
        call.enqueue(new Callback<RspModel<User>>() {
            @Override
            public void onResponse(Call<RspModel<User>> call, Response<RspModel<User>> response) {

                RspModel<User> body = response.body();
                if(response.code() == 401){
                    // 跳转登录界面
                    Log.e(TAG, "尚未登录");
                    AccountActivity.show(getApplication());
                    return;
                }
                if(body !=null && body.success()){
                    data = body.getData();
                    // String rspString = SimpleJsonTool.toJson(data); Log.e(TAG, rspString);
                    if(data != null && data.getUsername() != null && data.getUsername().length() > 0) {
                        mCircleTextImage.setImageUrl(data.getAvatar());;
                    }
                    mBinding.setUserInfo(data);
                    // 保存用户信息到数据库
                    DbHelper.save(User.class, data);

                }else {
                    Log.e(TAG, "request fail");
                }
            }

            @Override
            public void onFailure(Call<RspModel<User>> call, Throwable t) {
                Log.e(TAG, t.getMessage());
            }
        });
    }

    private void initView() {
        // 已经是好友 隐藏添加
        if(isBoolFriend){
            mAddFriend.setVisibility(View.GONE);
        }

        // 添加好友
        mAddFriend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                addFriend(talentsId);
            }
        });
        // 发送消息
        sendMessage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getChatPermission(talentsId, username);
            }
        });
        mRecycleView.setLayoutManager(new LinearLayoutManager(this));
        mRecycleView.addItemDecoration(new DividerItemDecoration(this,
                DividerItemDecoration.VERTICAL));
        Log.e(TAG, "list:" + mList.toString());

        mAdapter = new CommonAdapter<>(mList, new CommonAdapter.OnBindDataListener<UserPost>() {
            @Override
            public void onBindViewHolder(UserPost model, CommonViewHolder viewHolder, int type, int position) {
                fillData(model, viewHolder);
                digOrUndig(model, viewHolder);
                // 跳转详情
                viewHolder.getView(R.id.posts).setOnClickListener(v -> {
                    Intent intent = new Intent(getApplication(), PostDetailActivity.class);
                    intent.putExtra("postId", model.getId());
                    startActivity(intent);
                });
                viewHolder.getView(R.id.comment_num).setOnClickListener(v -> {
                    Intent intent = new Intent(getApplication(), PostDetailActivity.class);
                    intent.putExtra("postId", model.getId());
                    startActivity(intent);
                });
            }

            @Override
            public int getLayoutId(int type) {
                return R.layout.my_posts_item;
            }
        });
        mRecycleView.setAdapter(mAdapter);


        //监听列表滑动
        mRecycleView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }
        });
    }

    private void getChatPermission(String friendId, String username) {
        RemoteService service = Network.remote();
        Call<RspModel<ChatPermission>> call = service.chatPermission(friendId);
        call.enqueue(new Callback<RspModel<ChatPermission>>() {
            @Override
            public void onResponse(Call<RspModel<ChatPermission>> call, Response<RspModel<ChatPermission>> response) {
                RspModel<ChatPermission> body = response.body();
                //String rspString = SimpleJsonTool.toJson(body); Log.e(TAG, rspString);Log.e(TAG, friendId);

                if(response.code() == 401){
                    Log.e(TAG, "尚未登录");
                    AccountActivity.show(getApplication());
                    return;
                }
                if(body !=null && body.success()){
                    chatPermission = body.getData();
                    // BaseApplication.showToast("获取权限成功");
                    if(chatPermission.isBoolChat()){
                        MessageActivity.show(getApplication(), friendId, username,true);
                    } else {
                        // BaseApplication.showToast("暂无聊天权限");
                        MessageActivity.show(getApplication(), friendId, username,false);
                    }
                }
            }

            @Override
            public void onFailure(Call<RspModel<ChatPermission>> call, Throwable t) {

            }
        });
    }

    private void fillData(UserPost model, CommonViewHolder viewHolder) {
        viewHolder.setText(R.id.post_text, model.getContent());
        if(model.getPictureList() != null && !model.getPictureList().isEmpty()){
            viewHolder.setImageUrl(getApplication(), R.id.post_images, model.getPictureList().get(0));
        }else {
            viewHolder.goneIfEmpty(R.id.post_images);
        }
        viewHolder.setText(R.id.post_time, TimeUtils.calculate(model.getPublishTime()));
        // 开始喜欢
        if(model.getBoolLike()){
            viewHolder.setText(R.id.liked_num, String.valueOf(model.getLikeCount()));
            viewHolder.goneIfEmpty(R.id.like_num);
            viewHolder.show(R.id.liked_num);
        } else {
            viewHolder.setText(R.id.like_num, String.valueOf(model.getLikeCount()));
            viewHolder.goneIfEmpty(R.id.liked_num);
            viewHolder.show(R.id.like_num);
        }
        viewHolder.setText(R.id.comment_num, String.valueOf(model.getCommentCount()));
    }

    private void addFriend(String friendId) {
        RemoteService service = Network.remote();
        Call<RspModel<Boolean>> call = service.friendRequestSend(friendId,null,null);
        call.enqueue(new Callback<RspModel<Boolean>>() {
            @Override
            public void onResponse(Call<RspModel<Boolean>> call, Response<RspModel<Boolean>> response) {
                RspModel<Boolean> body = response.body();

                if(response.code() == 401){
                    Log.e(TAG, "尚未登录");
                    AccountActivity.show(getApplication());
                    return;
                }
                if(body !=null && body.success()){
                    BaseApplication.showToast("发送成功");
                }
            }

            @Override
            public void onFailure(Call<RspModel<Boolean>> call, Throwable t) {

            }
        });
    }

    protected void digOrUndig(UserPost model, CommonViewHolder viewHolder) {
        // 点赞
        viewHolder.getView(R.id.like_num).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                digPost(model.getId());
                viewHolder.goneIfEmpty(R.id.like_num);
                viewHolder.show(R.id.liked_num);
                int digNum = model.getBoolLike() ? model.getLikeCount() : model.getLikeCount()+1;
                // 开始喜欢 点赞 不变， 开始不喜欢 点赞+1
                viewHolder.setText(R.id.liked_num, String.valueOf(digNum));
            }
        });
        // 取消点赞
        viewHolder.getView(R.id.liked_num).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                unDigPost(model.getId());
                viewHolder.goneIfEmpty(R.id.liked_num);
                viewHolder.show(R.id.like_num);
                int digNum = model.getBoolLike() ? model.getLikeCount() - 1 : model.getLikeCount();
                // 开始喜欢 取消点赞 -1， 开始不喜欢 取消点赞不变
                viewHolder.setText(R.id.like_num, String.valueOf(digNum));

            }
        });
    }

    @OnClick(R.id.action_back)
    void back(){
        finish();
    }

    // 跳转资料设置
    @OnClick(R.id.resource_set)
    void clickMaterialSetting(){
        Intent intent = new Intent(this, MaterialSettingActivity.class);
        intent.putExtra("talentsId", data.getUserId());
        startActivity(intent);
    }

    // 动态点赞
    protected void digPost(String postId){
        RemoteService service = Network.remote();
        Call<RspModel<Boolean>> call = service.postLike(postId);
        call.enqueue(new Callback<RspModel<Boolean>>() {
            @Override
            public void onResponse(Call<RspModel<Boolean>> call, Response<RspModel<Boolean>> response) {

                RspModel<Boolean> body = response.body();
                if(response.code() == 401){
                    Log.e(TAG, "尚未登录");
                    AccountActivity.show(getApplication());
                    return;
                }
                if(body !=null && body.success()){
                    // BaseApplication.showToast("点赞成功");
                }else {
                    Log.e(TAG, "request fail");
                }
            }

            @Override
            public void onFailure(Call<RspModel<Boolean>> call, Throwable t) {
                Log.e(TAG, t.getMessage());
            }
        });
    }

    // 取消动态点赞
    protected void unDigPost(String postId){
        RemoteService service = Network.remote();
        Call<RspModel<Boolean>> call = service.postUnlike(postId);
        call.enqueue(new Callback<RspModel<Boolean>>() {
            @Override
            public void onResponse(Call<RspModel<Boolean>> call, Response<RspModel<Boolean>> response) {
                RspModel<Boolean> body = response.body();
                if(response.code() == 401){
                    Log.e(TAG, "尚未登录");
                    AccountActivity.show(getApplication());
                    return;
                }
                if(body !=null && body.success()){
                    // BaseApplication.showToast("取消点赞成功");
                }else {
                    Log.e(TAG, "request fail");
                }
            }

            @Override
            public void onFailure(Call<RspModel<Boolean>> call, Throwable t) {
                Log.e(TAG, t.getMessage());
            }
        });
    }
}